<?php

namespace App\Admin\Controllers\Stock;

use App\Admin\Actions\ExportExcel;
use App\Models\StockDepot;
use App\Models\StockDepotProduct;
use App\Models\StockProduct;
use App\Models\StockReport;
use App\Http\Controllers\Controller;
use App\Models\StockUnit;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class StockReportController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header(trans('出入库管理'))
            ->description(trans('出入库'))
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header(trans('出入库'))
            ->description(trans('出入库'))
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header(trans('admin.edit'))
            ->description(trans('出入库'))
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header(trans('admin.create'))
            ->description(trans('出入库'))
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StockReport);
        $grid->model()->orderByDesc('updated_at');
        $grid->disableColumnSelector();
        $grid->disableBatchActions();
        $grid->disableRowSelector();

        if (Admin::user()->depot_id){
            $depotList = StockDepot::where('id', Admin::user()->depot_id)->pluck('name', 'id')->toArray();
            $grid->model()->where('depot_id', Admin::user()->depot_id);
        }else {
            $depotList = StockDepot::all()->pluck('name', 'id')->toArray();
        }


        $grid->id('ID');
        $grid->sn('出入库单号');
        $grid->type('类型')->using([1=>'入库',2=>'出库']);
        $grid->author_id('操作员')->display(function ($realsed){
            $author = Administrator::find($realsed);
            return $author['name'];
        });
        $grid->column('depot_id','仓库')->using($depotList);;
//        $grid->status('状态');
        $grid->desc('备注');
        $grid->created_at(trans('admin.created_at'));
        $grid->updated_at(trans('admin.updated_at'));

        $grid->disableCreateButton();
        $grid->filter(function ($filter) use ($depotList){
            $filter->expand();
            $filter->column(1/2, function ($filter) {
                $filter->equal('type','类型')->select([1=>'入库',2=>'出库']);
            });
            $filter->column(1/2, function ($filter) use ($depotList) {
                $filter->equal('depot_id','仓库')->select($depotList);
            });
            $filter->disableIdFilter();// 去掉默认的id过滤器
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->add(new ExportExcel());
            $actions->disableEdit();
            $actions->disableDelete();
        });
        return $grid;
    }

    public function export(){
        $report_id = $this->request->input('report');
        if (!$report_id){
            return back()->withErrors('参数错误');
        }
        foreach (StockUnit::all() as $unit){
            $unitList[$unit['id']] = $unit['name'];
        }
        $reportInfo = StockReport::find($report_id);


        $type_name = $reportInfo['type'] == 1? '入库单': '出库单';
        $title = $reportInfo['depot_name'].$type_name.$reportInfo['created_at'];
//        $depotInfo = StockDepot::find($reportInfo['depot_id']);
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getDefaultRowDimension()->setRowHeight(28);
        $worksheet->setTitle('reports');

        $worksheet->setCellValueByColumnAndRow(1, 1, $title);
        $worksheet->mergeCells("A1:F1");
        $worksheet->setCellValue('A1', '湖南小黄鸭科技有限公司('.$type_name.')');

//        $worksheet->getRowDimension(1)->setRowHeight(25);
        $worksheet->setCellValue('A2', '序号');
        $worksheet->setCellValue('B2', '产品名称');
        $worksheet->setCellValue('C2', '规格型号');
        $worksheet->setCellValue('D2', '数量');
        $worksheet->setCellValue('E2', '单位');
        $worksheet->setCellValue('F2', '备注');
//        $worksheet->getRowDimension(2)->setRowHeight(25);


        $worksheet->getColumnDimension('A')->setWidth(5);
        $worksheet->getColumnDimension('B')->setWidth(30);
        $worksheet->getColumnDimension('C')->setWidth(50);
        $worksheet->getColumnDimension('D')->setWidth(8);
        $worksheet->getColumnDimension('E')->setWidth(8);
        $worksheet->getColumnDimension('F')->setWidth(20);

        $row = 3;
        collect($reportInfo['products'])->map(function ($res) use (&$row, &$worksheet, $unitList) {
//            $worksheet->getRowDimension($row)->setRowHeight(25);
            $worksheet->setCellValueByColumnAndRow(1, $row, $row-2);
            $worksheet->setCellValueByColumnAndRow(2, $row, $res['name']);
            $worksheet->setCellValueByColumnAndRow(3, $row, $res['spec']);
            $worksheet->setCellValueByColumnAndRow(4, $row, $res->pivot['product_count']);
            $worksheet->setCellValueByColumnAndRow(5, $row, $unitList[$res['unit']]);
            $worksheet->setCellValueByColumnAndRow(6, $row, $res->pivot['product_desc']);
            $row++;
        });


        $worksheet->setCellValue('A'.$row, '备注');
        $worksheet->setCellValue('B'.$row, $reportInfo['desc']);
        $worksheet->mergeCells("B".$row.":F".$row);
        $row++;

        $worksheet->setCellValue('A'.$row, '制表');
        $worksheet->mergeCells("A".$row.":B".$row);
        $worksheet->setCellValue('C'.$row, '日期');
        $worksheet->mergeCells("D".$row.":E".$row);
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => 'FF000000'],
                ],
            ],
            'alignment' => [
                'vertical'=>\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ],
        ];
        $worksheet->getStyle('A1:F'.$row)->applyFromArray($styleArray);

        for ($i = 0; $i <= $row; $i++){
            $worksheet->getRowDimension($row)->setRowHeight(28);
        }

        $this->downForBrowser($title, $spreadsheet);
        return true;
    }

    /**
     * @param $param string
     * @param $spreadsheet Spreadsheet
     */
    public function downForBrowser($filename, Spreadsheet $spreadsheet)
    {
        $file_name = $filename . ".xlsx";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit();
    }
    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(StockReport::findOrFail($id));

        $unitList = [];
        foreach (StockUnit::all() as $item){
            $unitList[$item['id']] = $item['name'];
        }

        $depotList = [];
        StockDepot::all()->each(function ($item) use (&$depotList){
            $depotList[$item['id']] = $item['name'];
        });

        $show->id('ID');
        $show->sn('出入库单号');
        $show->type('类型')->using([1=>'入库',2=>'出库']);
        $show->author_id('操作员')->as(function ($realsed){
            $author = Administrator::find($realsed);
            return $author['name'];
        });
        $show->depot_id('仓库')->as(function ($realsed){
            $depot = StockDepot::find($realsed);
            return $depot['name'];
        });
        $show->desc('备注');
        $show->products('产品', function (Grid $products) use ($unitList) {
            $products->id('ID');
            $products->name('产品名称');
            $products->spec('规格');
            $products->desc('产品备注');
            $products->price('价格');
            $products->product_count('数量');
            $products->unit('单位')->using($unitList);

            $products->disableActions();
            $products->disableBatchActions();
            $products->disableFilter();
            $products->disableColumnSelector();
            $products->disableCreateButton();
            $products->disableExport();
            $products->disableTools();
            $products->disablePagination();
        });
        $show->created_at(trans('admin.created_at'));
        $show->updated_at(trans('admin.updated_at'));


        $show->panel()->tools(function ($tools) {
//            $tools->disableList();
            $tools->disableEdit();
            $tools->disableDelete();
        });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function form()
    {
        $form = new Form(new StockReport);

        if (session('errors')){
            $message = session('errors')->all();
            admin_toastr($message, 'error');
        }

        if (Admin::user()->depot_id){
            $depotList = StockDepot::where('id', Admin::user()->depot_id)->get()->pluck('name', 'id')->toArray();
        }else {
            $depotList = StockDepot::all()->pluck('name', 'id')->toArray();
        }
        $depot_id = $this->request->input("depot_id", $form->depot_id);
        if (!$depot_id){
            return back()->withInput()->withErrors("参数错误");
        }
        if (!$type= $this->request->input("type")){
            return back()->withInput()->withErrors("参数错误");
        }
        $depotInfo = StockDepot::find($depot_id);

        $form->text('sn', '单号')->default(date('YmdHis').rand(1000, 9999))->readonly();
        $form->select('type', '类型')->options([1=>'入库',2=>'出库'])->default($type)->readonly();
        $form->text('depot_name', '仓库')->default($depotInfo['name'])->readonly();

        $form->hidden('depot_id', '仓库')->default($depotInfo['id']);

        $form->table('products', '产品', function ($table) use ($depot_id, $type) {
            if ($type == 2) {
                $productCol = StockProduct::with('depot')->whereHas('depot', function ($query) use ($depot_id) {
                    $query->where('depot_id', $depot_id);
                })->get();
            }else{
                $productCol = StockProduct::all();
            }

            $productList = [];
            foreach ($productCol as $pro){
                $productList[$pro['id']] =  $pro['name'].'('.$pro['sn'].')'.$pro['brand'];
            }

            $table->select('product_id','产品名称')->options($productList)->rules('numeric');
            $table->decimal('product_count','产品数量')->rules('numeric');
            $table->decimal('product_price','价格')->rules('numeric');
            $table->text('product_desc','产品备注');
        });

        $form->textarea('desc', '备注');
        $form->hidden('author_id')->default(Admin::user()->id);

        $form->saving(function (Form $form){
            DB::beginTransaction();
        });
        $form->saved(function (Form $form){
            if ($form->model()->products()->count() <= 0){
                DB::rollBack();
                return back()->withInput()->withErrors("请添加产品");
            }

            foreach ($form->model()->products as $product){
                if (!$stockDepotProduct = StockDepotProduct::where(['depot_id'=>$form->depot_id, 'product_id'=>$product->pivot['product_id']])->firstOrNew()){
                    $stockDepotProduct = new StockDepotProduct();
                }
                if ($form->type == 1){
                    $stockDepotProduct->num = $stockDepotProduct['num'] + $product->pivot['product_count'];
                    $stockDepotProduct->depot_id = $form->depot_id;
                    $stockDepotProduct->product_id = $product->pivot['product_id'];
                    $stockDepotProduct->save();
                }else{
                    if ($stockDepotProduct['num'] - $product->pivot['product_count'] < 0){
                        DB::rollBack();
                        return back()->withInput()->withErrors("产品库存不足");
                    }
                    $stockDepotProduct->num = $stockDepotProduct['num'] - $product->pivot['product_count'];
                    $stockDepotProduct->depot_id = $form->depot_id;
                    $stockDepotProduct->product_id = $product->pivot['product_id'];
                    $stockDepotProduct->save();
                }
            }
            DB::commit();
        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        return $form;
    }
}
